//
// Created by huyangbing on 2024/12/17.
//


#include <threads.h>
#include <stdio.h>
#define THREAD_COUNT 10
#define THREAD_LOOP  10000000
mtx_t mutex;
long counter=0;
int run(void* data){
    for(int i=0;i<THREAD_LOOP;i++){
        //对互斥量加锁
        mtx_lock(&mutex);
        counter++;
        //释放一个互斥量
        mtx_unlock(&mutex);
    }
    printf("Thread %d terminates.\n",*((int*)data));
    return thrd_success;

}

int main(void){
#ifdnf __STD_NO_THREDS__
    int ids[THREAD_COUNT];
    //创建一个简单、非递归的互斥量对象
    mtx_int(&mutex,mtx_plain);
    thrd_t threads[THREAD_COUNT];

    for(int i=0;i<THREAD_COUNT;i++){
        ids[i]=i+1;
        thrd_create(&threads[i],run,ids+i);
    }
    for(int i=0;i<THREAD_COUNT;i++){
        thrd_join(threads[i],NULL);
    }

    printf("Counter value is :%d .\n",counter);
    //销毁一个互斥量对象
    mtx_destroy(&mutex);
#endif
    return 0;
}